﻿using System;
using System.IO;
using System.Text;
using System.Threading;

namespace RaceHFTools.Utils
{
    public static class Log
    {
        private static Semaphore busy = null;
        private static readonly string nextline = "\r\n";
        private static string logfile;
        private static FileStream logfs;

        public static void Open(string path)
        {
            logfile = path;
            if (busy == null)
                busy = new Semaphore(1, 1);
            logfs = new FileStream(logfile, FileMode.Create);
        }

        public static void Close()
        {
            busy?.Dispose();
            busy = null;
            logfs.Close();
        }

        static void write_to_file(string txt)
        {
            byte[] btxt = Encoding.UTF8.GetBytes(txt);
            busy?.WaitOne();
            logfs.Write(btxt, 0, btxt.Length);
            busy?.Release();
        }

        public static void Write(string str)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append($"{DateTime.Now}.{DateTime.Now.Millisecond} ");
            sb.Append(str);
            sb.Append(nextline);

            write_to_file(sb.ToString());
        }

        #nullable enable
        public static void Write(string title, byte[]? array)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append($"{DateTime.Now}.{DateTime.Now.Millisecond} ");
            sb.Append(title);
            if (array != null)
            {
                for (int i = 0; i < array.Length; i++)
                    sb.AppendFormat("{0:X02} ", array[i]);
            }
            sb.Append(nextline);

            write_to_file(sb.ToString());
        }
    }
}
